import axios from 'axios';
import { Message, Loading } from 'element-ui';

// 请求超时时间 & 允许你cookie跨域 & 多环境打包配置

const service = axios.create({
  baseURL: 'http://123.57.178.137:3000/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

//初始化loading
let loading;

//开始加载动画
function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '拼命加载中...'
  });
}
// 结束加载动画
function endLoading() {
  loading.close();
}

// 请求拦截  设置统一header
service.interceptors.request.use(
  config => {
    // 加载
    // startLoading();
    if (localStorage.token) {
      config.headers['token'] = localStorage.token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截  401 token过期处理
service.interceptors.response.use(
  response => {
    // endLoading();
    return response.data;
  },
  error => {
    // 错误提醒
    // endLoading();
    Message.error('error');

    // const { status } = error.response;
    // if (status == 401) {
    //   Message.error('token已失效，请重新登录');
    //   // 清除token
    //   localStorage.removeItem('token');

    //   // 页面跳转
    //   this.$router.push('/login');
    // }
    return Promise.reject(error);
  }
);

export default service
